<?php
namespace Douyin\Open;
class Dy
{
    private $clientKey;
    private $clientSecret;
    private $scope;
    private $redirect_uri;
    private $apiUrl;
    /**
     * 构造配置项
     **/
    public function __construct($config = array())
    {
        $this->clientKey = isset($config['client_key']) ? $config['client_key'] : '';
        $this->clientSecret = isset($config['client_secret']) ? $config['client_secret'] : '';
        $this->scope = isset($config['scope']) ? $config['scope'] : '';
        $this->redirect_uri = isset($config['redirect_uri']) ? $config['redirect_uri'] : '';
        $this->apiUrl = isset($config['apiUrl']) ? $config['apiUrl'] : '';
    }
    /**
     * 用户授权登录
     **/
    public function Dy_login()
    {
        $path=$this->apiUrl.'/platform/oauth/connect?client_key='.$this->clientKey.'&response_type=code&scope='.$this->scope.'&redirect_uri='.$this->redirect_uri.'&state=1';
        header('Location:' . $path);
        exit();
    }
    /**
     * 获取access_token
     * code用户授权码
     **/
    public function Dy_access_token($code){
        $data=array(
            'client_secret'=>$this->clientSecret,
            'code'=>$code,
            'grant_type'=>'authorization_code',
            'client_key'=>$this->clientKey
        );
        return json_decode($this->send_post('/oauth/access_token/',$data))->data;
    }
    /**
     * 刷新refresh_token
     * refresh_token为获取access_token返回的refresh_token值
     **/
    public function Dy_refresh_token($refresh_token){
        $data=array(
            'client_key'=>$this->clientKey,
            'refresh_token'=>$refresh_token
        );
        return json_decode($this->send_post('/oauth/access_token/',$data))->data;
    }
    /**
     * 生成client_token
     **/
    public function Dy_client_token(){
        $data=array(
            'client_key'=>$this->clientKey,
            'client_secret'=>$this->clientSecret,
            'grant_type'=>'client_credential'
        );
        return json_decode($this->send_post('/oauth/client_token/',$data))->data;
    }
    /**
     * 刷新access_token
     * refresh_token为获取access_token返回的refresh_token值
     **/
    public function Dy_sx_access_token($refresh_token){
        $data=array(
            'client_key'=>$this->clientKey,
            'grant_type'=>'refresh_token',
            'refresh_token'=>$refresh_token
        );
        return json_decode($this->send_post('/oauth/access_token/',$data))->data;
    }
    /**
     * 静默获取授权，通过login_id
     **/
    public function login_id ($state){

    }
    /**
     * 获取用户公开信息
     * access-token: 调用/oauth/access_token/生成的token，此token需要用户授权。
     **/
    public function Dy_userinfo($access_token){
        $data=array(
            'access_token'=>$access_token,
            'open_id'=>'refresh_token'
        );
        return $this->json(json_decode($this->send_post('/oauth/userinfo/',$data))->data);
    }
    /**
     * 手机号码解密,授权返回encrypt_mobile
     **/
    public function Dy_decrypt_mobile($encrypted_mobile){
        $iv = substr($this->clientSecret, 0, 16);
        return openssl_decrypt($encrypted_mobile, 'aes-256-cbc', $this->clientSecret, 0, $iv);
    }
    /**
     * 获取粉丝列表&获取关注粉丝
     * url SDK类型
     * access-token  调用/oauth/access_token/生成的token，此token需要用户授权
     * open_id  通过/oauth/access_token/获取，用户唯一标志
     * cursor  分页游标, 第一页请求cursor是0
     * count  每页数量
     **/
    public function Dy_fans_list($url,$access_token,$open_id,$cursor,$count){
        $path=$url.'?open_id='.$open_id.'&cursor='.$cursor.'&count='.$count;
        return $this->json(json_decode($this->send_get($path,$access_token))->data);
    }
    /**
     * 粉丝判断
     * access-token  调用/oauth/access_token/生成的token，此token需要用户授权
     * open_id  通过/oauth/access_token/获取，用户唯一标志
     * follower_open_id  粉丝开放ID
     **/
    public function Dy_fans_check($access_token,$open_id,$follower_open_id){
        $path='/fans/check/?open_id='.$open_id.'&follower_open_id='.$follower_open_id;
        return $this->json(json_decode($this->send_get($path,$access_token))->data);
    }
    /**
     * 用户数据
     * url SDK类型
     * open_id   通过/oauth/access_token/获取，用户唯一标志
     * date_type  近7/15天；输入7代表7天、15代表15天、30代表30天
     * access-token  调用/oauth/access_token/生成的token
     **/
    public function Dy_user_video($url,$open_id,$date_type,$access_token){
        $path=$url.'?open_id='.$open_id.'&date_type='.$date_type;
        return $this->json(json_decode($this->send_get($path,$access_token))->data);
    }
    /**
     * 视频数据
     * url SDK类型
     * access-token  调用/oauth/access_token/生成的token
     * open_id   通过/oauth/access_token/获取，用户唯一标志
     * item_id   注意参数中item_id作为url参数时，必须encode，只对item_id单独进行encode。
     * access-token  调用/oauth/access_token/生成的token
     **/
    public function Dy_video($url,$open_id,$item_id,$access_token,$date_type){
        $path=$url.'?open_id='.$open_id.'&item_id='.$item_id.'&date_type='.$date_type;
        return $this->json(json_decode($this->send_get($path,$access_token))->data);
    }
    /**
     * 粉丝画像
     * url SDK类型
     * access-token  调用/oauth/access_token/生成的token
     * open_id   通过/oauth/access_token/获取，用户唯一标志
     **/
    public function Dy_fans($url,$access_token,$open_id){
        $path=$url.'?open_id='.$open_id;
        return $this->json(json_decode($this->send_get($path,$access_token))->data);
    }
    /**
     * 获取上升词&实时热点词（后者需传入2个空值）
     * access-token  调用/oauth/client_token/生成的token
     **/
    public function Dy_hotsearch($access_token,$cursor,$count){
        $path='/hotsearch/trending/sentences/?cursor='.$cursor.'&count='.$count;
        return $this->json(json_decode($this->send_get($path,$access_token))->data);
    }
    /**
     * 热点词聚合
     * access-token 调用/oauth/client_token/生成的 token
     **/
    public function Dy_videos($access_token,$hot_sentence){
        $path='/hotsearch/videos/?hot_sentence='.$hot_sentence;
        return $this->json(json_decode($this->send_get($path,$access_token))->data);
    }
    /**
     * 星图榜单数据
     * access-token  调用/oauth/client_token/生成的token
     * hot_list_type   达人热榜类型 * `1` - 星图指数榜 * `2` - 涨粉指数榜 * `3` - 性价比指数榜 * `4` - 种草指数榜 * `5` - 精选指数榜 * `6` - 传播指数榜
     **/
    public function Dy_hot_list_type($access_token,$hot_list_type){
        $path='/star/hot_list/?hot_list_type='.$hot_list_type;
        return $this->json(json_decode($this->send_get($path,$access_token))->data);
    }
    /**
     * 星图达人
     * access-token 调用/oauth/access_token/生成的token
     **/
    public function Dy_author_score($access_token,$open_id){
        $path='/star/author_score/?open_id='.$open_id;
        return $this->json(json_decode($this->send_get($path,$access_token))->data);
    }
    /**
     * 星图达人指数v2
     * access-token 调用/oauth/client_token/生成的token
     **/
    public function Dy_author_score_v2($access_token,$unique_id){
        $path='/star/author_score/?unique_id='.$unique_id;
        return $this->json(json_decode($this->send_get($path,$access_token))->data);
    }
    /**
     * 影视排行
     * access-token  调用/oauth/client_token/生成的token
     * type  榜单类型： * 1 - 电影 * 2 - 电视剧 * 3 - 综艺
     * version 榜单版本：空值默认为本周榜单
     **/
    public function Dy_discovery($access_token,$type,$version){
        $path='/discovery/ent/rank/item/?type='.$type.'&version='.$version;
        return $this->json(json_decode($this->send_get($path,$access_token))->data);
    }
    /**
     * 影视综合排行
     * access-token  调用/oauth/client_token/生成的token
     **/
    public function Dy_version($access_token,$type,$count,$cursor){
        $path='/discovery/ent/rank/version/?type='.$type.'&count='.$count.'&cursor='.$cursor;
        return $this->json(json_decode($this->send_get($path,$access_token))->data);
    }
    /**
     * 热点视频&获取热门榜单数据
     * url  抖音榜单分类open-sdk
     * access-token  调用/oauth/client_token/生成的token
     **/
    public function Dy_hot($url,$access_token){
        return $this->json(json_decode($this->send_get($url,$access_token))->data);
    }
    /**
     * get请求
     **/
    private function send_get($url,$access_token){
        $data = array(
            'Content-Type:application/json',
            'access-token:'.$access_token,
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->apiUrl.$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 2);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        if ($data) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $data);
        }
        $out = curl_exec($ch);
        curl_close($ch);
        return $out;
    }
    /**
     * post请求
     **/
    private function send_post($url,$data){
        $post_data = http_build_query($data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $post_data,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($this->apiUrl.$url, false, $context);
        return $result;
    }
    /**
     * 数据回调处理
     * data    返回未处理的数据
     **/
    private function json($data){
        if($data->error_code=='0'){
            if($data->list){
                $res['data']=$data->list;
            }else if($data->fans_data){
                $res['data']=$data->fans_data;
            }else if($data->result_list){
                $res['data']=$data->result_list;
            }else{
                $res['data']=$data;
            }
            $res['status']='1';
            $res['msg']='成功';
        }else{
            $res['status']=$data->error_code;
            $res['data']='';
            $res['msg']=$data->description;
        }
        return $res;
    }
}
